from django.shortcuts import render # type: ignore

# Create your views here.
from django.shortcuts import render # type: ignore
from django.http import JsonResponse # type: ignore
from .models import ChatMessage
from .spark_api import SparkAPI

def chat_view(request):
    if request.method == 'POST':
        # 获取用户输入
        user_input = request.POST.get('message', '')
        
        # 调用星火API（真实凭证）
        spark = SparkAPI(
            app_id="1363f7ea",
            api_key="a427594f5e0fe7513bba5ec5c4f760ac",
            api_secret="NzdiM2UyZmQ2NDUwMDQwZGFhMDMyZTA5"
        )
        ai_response = spark.get_response(user_input)
        
        # 保存记录
        ChatMessage.objects.create(
            user_input=user_input,
            ai_response=ai_response
        )
        
        return JsonResponse({'response': ai_response})
    
    # GET请求显示聊天记录
    messages = ChatMessage.objects.all().order_by('-created_at')[:10]
    return render(request, 'chat.html', {'messages': messages})